<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "gky_writings".
 *
 * @property string $id
 * @property string $writingname
 * @property string $writingno
 * @property string $publishdate
 * @property string $author
 * @property string $writinglevel
 * @property string $mark
 * @property string $updatetime
 * @property integer $isfinish
 * @property string $addman
 * @property string $addmanid
 * @property string $addtime
 * @property string $writingtype
 */
class Writings extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gky_writings';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['isfinish','publishdate','writingno'], 'safe'],
            [[ 'addmanid'], 'integer'],
            [['writingname', 'author'], 'string', 'max' => 255],
            [['writinglevel', 'addman', 'writingtype'], 'string', 'max' => 64],
            [['mark'], 'string', 'max' => 1024],
            [['updatetime', 'addtime'], 'safe'],
            //添加验证
            [[ 'writingname'], 'required']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'writingname' => '著作名称',
            'writingno' => '著作编号',
            'publishdate' => '发表日期',
            'author' => '作者',
            'writinglevel' => '获奖等级',
            'mark' => '备注',
            'updatetime' => '更新时间',
            'isfinish' => '是否完成',
            'addman' => '添加人',
            'addmanid' => '添加人id',
            'addtime' => '添加时间',
            'writingtype' => '著作类型',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            //添加修改人的信息 由于这部分没有必要自己填写 所以直接获取登录人的信息  在保存的时候设置就好
            $id = Yii::$app->user->identity->id;
            //添加人的id
            $this->addmanid = $id;
            //添加人的姓名
            $name = GkyUser::find()->where(['id' => $id])->one()->username;
            $this->addman = $name;
            //更新时间
            $time = date("Y-m-d");
            $this->updatetime = $time;
            //添加时间
            $this->addtime = $time;
            return true;
        } else {
            return false;
        }
    }

    /**
     * 查询著作列表，返回字段为著作名，作者，添加时间
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getList($pageNow, $pageSize){

        $list = Writings::find()
            ->addSelect(['id','writingname','author','addtime'])
            ->addOrderBy(['addtime' => SORT_DESC])
            ->offset(($pageNow - 1) * $pageSize)
            ->limit($pageSize)
            ->all();
        return $list;
    }

}
